<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="类型" prop="typeid">
          <el-select 
            v-model="queryParams.typeid" 
            placeholder="请选择或搜索类型" 
            clearable
            filterable
            remote
            :remote-method="handleTypeSearch"
            :loading="typeLoading"
            style="width: 200px"
          >
            <el-option
              v-for="item in categoryOptions"
              :key="item.id"
              :label="item.categoryName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
    
     
   
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['goods:products:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['goods:products:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['goods:products:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['goods:products:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="productsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="商品名称" align="center" prop="productName" show-overflow-tooltip="true" />
      <el-table-column label="库存" align="center" prop="stock" />
      <el-table-column label="商品简介" align="center" prop="detail" show-overflow-tooltip="true">
  <template slot-scope="scope">
    <span v-html="removeParagraphTags(scope.row.detail)"></span>
  </template>
</el-table-column>
      <el-table-column label="兑换详情" align="center" prop="description" show-overflow-tooltip="true">
  <template slot-scope="scope">
    <span v-html="removeParagraphTags(scope.row.description)"></span>
  </template>
</el-table-column>

      <el-table-column label="分类名称" align="center" prop="productCategories.categoryName">
        
        </el-table-column>
      
       
      <el-table-column align="center" label="商品图片链接" width="120" :height="50" :show-overflow-tooltip="true" prop="image_url">
    <template scope="scope">
        <el-popover
                placement="right"
                title=""
                trigger="hover">
            <el-image slot="reference" :src="scope.row.image" :alt="scope.row.image" style="max-height: 200px;max-width: 200px"></el-image>
            <el-image :src="scope.row.image" ></el-image>
        </el-popover>
    </template>
</el-table-column>

      <el-table-column label="价格" align="center" prop="pointsPrice" />
      <el-table-column label="销售数量" align="center" prop="sales.saleQuantity" />
      <el-table-column label="活动" align="center" prop="state" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.huodong" :value="scope.row.state"/>
        </template>
        </el-table-column>
      <el-table-column label="上架时间" align="center" prop="publishedTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.publishedTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
   
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['goods:products:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['goods:products:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品名称" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品库存" prop="stock">
          <el-input v-model="form.stock" placeholder="请输入商品库存，必须大于等于0" />
        </el-form-item>
        <el-form-item label="商品简介">
          <editor v-model="form.detail" :min-height="192"/>
        </el-form-item>
        <el-form-item label="商品描述">
          <editor v-model="form.description" :min-height="192"/>
        </el-form-item>
      
        <el-form-item label="商品图片链接" prop="image">
          <image-upload v-model="form.image"/>
        </el-form-item>
        <el-form-item label="分类" prop="typeid">
          <el-select v-model="form.typeid" placeholder="请选择题目分类" style="width: 100%">
            <el-option
              v-for="item in categoryOptions"
              :key="item.id"
              :label="item.categoryName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="是否参加活动" prop="state">
          <el-select v-model="form.state" placeholder="请选择是否参加活动">
            <el-option
              v-for="dict in dict.type.huodong"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="商品价格" prop="pointsPrice">
          <el-input v-model="form.pointsPrice" placeholder="请输入商品价格，以积分表示" />
        </el-form-item>
      
      
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProducts, getProducts, delProducts, addProducts, updateProducts } from "@/api/goods/products";
import { listCategories } from "@/api/categories/categories.js";
export default {
  name: "Products",
  dicts: ['goods'],
  dicts: ['huodong'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品管理表格数据
      productsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 分类选项
      categoryOptions: [],
      // 类型选项
      typeOptions: [],
      // 分类搜索加载中
      categoryLoading: false,
      // 类型搜索加载中
      typeLoading: false,
    
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productName: null,
        stock: null,
        description: null,
        image: null,
        pointsPrice: null,
        publishedTime: null,
        isDeleted: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        id: [
          { required: true, message: "商品唯一标识符，自增不能为空", trigger: "blur" }
        ],
        productName: [
          { required: true, message: "商品名称不能为空", trigger: "blur" }
        ],
        stock: [
          { required: true, message: "商品库存，必须大于等于0不能为空", trigger: "blur" }
        ],
        description: [
          { required: true, message: "商品描述不能为空", trigger: "blur" }
        ],
        image: [
          { required: false, message: "商品图片链接不能为空", trigger: "blur" }
        ],
        pointsPrice: [
          { required: true, message: "商品价格，以积分表示不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getCategoryOptions();
  },
  methods: {
    /** 查询商品管理列表 */
    getList() {
      this.loading = true;
      listProducts(this.queryParams).then(response => {
        this.productsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    removeParagraphTags(description) {
    if (description) {
      return description.replace(/<\/?p>/g, ''); // 去掉 <p> 标签
    }
    return '';
  },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        productName: null,
        stock: null,
        description: null,
        image: null,
        pointsPrice: null,
        publishedTime: null,
        typeid:null,
        isDeleted: null,
        detail:null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)

      this.single = selection.length!==1
      this.multiple = !selection.length
    },

     /** 获取分类选项 */
     getCategoryOptions() {
      this.categoryLoading = true;
      listCategories({ pageSize: 100 }).then(response => {
        this.categoryOptions = response.rows; // 获取分类数据并存储
        this.categoryLoading = false;
      });
    },
    
       /** 处理分类搜索 */
       handleCategorySearch(query) {
      if (query !== '') {
        this.getCategories(query);
      } else {
        this.getCategories();
      }
    },
 
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getCategoryOptions();
      this.open = true;
      this.title = "添加商品管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getProducts(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改商品管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateProducts(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProducts(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除商品管理编号为"' + ids + '"的数据项？').then(function() {
        return delProducts(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('goods/products/export', {
        ...this.queryParams
      }, `products_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style>

</style>
